<template>
    <div class="address-select-root">
        <el-cascader :options="options" v-model="selectedOptions" @change="handleChange" :disabled="disabled"
            :style="{ width: minWidth + 'px' }">
        </el-cascader>
    </div>
</template>
  
<script setup>
import { regionData, codeToText } from 'element-china-area-data';
import { watch, defineEmits } from 'vue';

const emit = defineEmits(['change'])
const props = defineProps({
    minWidth: {
        type: String,
        default: '270'
    },
    separateTxt: {
        type: String,
        default: '-'
    },
    disabled: {
        type: Boolean,
        default: false
    },
    defaultAddress: {
        type: Array,
        default: () => {
            return []
        }
    }
})

watch(() => props.defaultAddress, value => reSet(value))

const options = ref(regionData)
const selectedOptions = ref([])


const reSet = (value) => {
    if (value && value.length > 0) {
        selectedOptions.value = value
    }
}
reSet(props.defaultAddress)


const handleChange = (val) => {
    if (val) {
        let address = ''
        let codes = []
        let result = []
        for (let i = 0; i < val.length; i++) {
            let str = codeToText[val[i]]
            result.push({
                name: str,
                value: val[i]
            })
            codes.push(val[i])
            if (address.length > 0) {
                address += props.separateTxt + str
            } else {
                address = str
            }
        }
        emit('change', { result, address, codes })
    }
}

</script>
  
<style lang='scss' scoped>
.address-select-root {
    width: 100%;
}
</style>